﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PDX.Services
{
    /// <summary>
    /// Defines some singletons that are used by the default <see cref="RegistrationBuilder"/>
    /// </summary>
    public static class Singletons
    {
        /// <summary>
        /// Gets or sets the service provider.
        /// Typically an <see cref="IAttacher{T}"/> uses this to lookup services
        /// and does "poor man's DI" into whatever it is attaching.
        /// </summary>
        /// <value>
        /// The service provider.
        /// </value>
        public static IServiceProvider ServiceProvider { get; set; }

        /// <summary>
        /// Gets or sets the property model factory.
        /// </summary>
        /// <value>
        /// The property model factory.
        /// </value>
        public static ContextManagement.IPropertyModelFactory PropertyModelFactory { get; set; }

        /// <summary>
        /// Gets or sets the notification manager factory.
        /// </summary>
        /// <value>
        /// The notification manager factory.
        /// </value>
        public static Notification.INotificationManagerFactory NotificationManagerFactory { get; set; }

        /// <summary>
        /// Gets or sets the property resolver.
        /// </summary>
        /// <value>
        /// The property resolver.
        /// </value>
        public static ContextManagement.IPropertyResolver PropertyResolver { get; set; }

        static Singletons()
        {
            PropertyModelFactory = new ContextManagement.DefaultPropertyModelFactory();
            NotificationManagerFactory = new Notification.DefaultNotificationManagerFactory();
            PropertyResolver = new ContextManagement.DefaultPropertyResolver();
            

            Context.OnConstructed += (s, e) =>
            {
                foreach (var attacher in ServiceProvider.ResolveAll<IAttacher<Context>>())
                {
                    attacher.Attach(e.Data);
                }
            };

            Element.OnConstructed += (s, e) =>
            {
                foreach (var attacher in ServiceProvider.ResolveAll<IAttacher<Element>>())
                {
                    attacher.Attach(e.Data);
                }
            };

            var instance = new ServiceProvider();
            new RegistrationBuilder(instance).RegisterAll();
            ServiceProvider = instance;
        }
    }
}
